export default class BaseComponent
{
    //属性。若其中涉及后期变化的值，那些值在后期变化时不能拿Properties，而要事先备份在元素中，因为Properties是同一类标签共用的，只在渲染时取实际值
    Properties = { _: null };

    //放置InnerHTML的容器(jquery选择)
    InnerContainer = null;

    //读完当前组件实例的所有属性了，在替换前做的最后工作。elem是用户自义的标签元素
    preRender(elem) { }

    //替换后的工作。replacing是解析后的元素
    postRender(replacing) { }

    render(name)
    {
        while ($(`${name}, ${name.replace(/_/g, "-")}`).length > 0)
            $(`${name}, ${name.replace(/_/g, "-")}`).each((_, elem) =>
            {
                var properties = JSON.stringify(this.Properties);		//备份class中定义的初始值

                for (var key in this.Properties)
                    if (elem.getAttribute(key) != null)
                        this.Properties[key] = elem.getAttribute(key);

                this.preRender(elem);				//elem是自定义标签

                var replacing = $(this.Content.format(this.Properties));
                if (this.InnerContainer != null)
                    replacing.find(this.InnerContainer).html(elem.innerHTML);
                elem.replaceWith(replacing[0]);

                this.postRender(replacing[0]);		//replacing[0]是解析后的内容

                this.Properties = JSON.parse(properties);				//还原class中定义的初始值给后面的同类元素使用
            });
    }
}

String.prototype.format = function (args)
{
    if (arguments.length == 0) return this;

    var result = this;
    if (arguments.length == 1 && typeof (args) == "object")
        for (var key in args)
            result = result.replace(new RegExp("({" + key + "})", "g"), args[key]);
    else
        for (var i = 0; i < arguments.length; i++)
            if (arguments[i] == undefined)
                return "";
            else
                result = result.replace(new RegExp("({[" + i + "]})", "g"), arguments[i]);

    return result;
}
